﻿using Castle.MicroKernel.Registration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using System.Configuration;
using System.IO;
using System.Reflection;

namespace Shape.Mvp.Persistence
{
	class HibernateHelper
	{
		private static ISessionFactory _currentSessionFactory;

		internal static ISessionFactory GetSessionFactory()
		{
			if (_currentSessionFactory == null)
			{
				string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;

				_currentSessionFactory =
					Fluently.Configure()
						.Database(
							MsSqlConfiguration.MsSql2008.ConnectionString(connectionString).ShowSql())
						.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetEntryAssembly()))
					//.ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
						.ExposeConfiguration(cfg => cfg.SetProperty(
														Environment.CurrentSessionContextClass,
														"Shape.Mvp.Persistence.Conversations.Hibernate.ThreadLocalConversationalSessionContext, Shape.Mvp"))
						.BuildSessionFactory();

			}

			return _currentSessionFactory;
		}
	}
}
